package com.it.cloud.modules.feignTest.service;

import com.it.cloud.modules.feignTest.config.FeignConfig;
import feign.hystrix.FallbackFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

// fallback方式简单，但是获取不到HTTP请求错误状态码和信息
// @FeignClient(name = "SERVICE-HI", configuration = FeignConfig.class, fallback = FeignFallbackHystric.class)

@FeignClient(name = "SERVICE-HI", configuration = FeignConfig.class, fallbackFactory = FeignFallbackFactoryHystric.class)
public interface IFeignService {

    @GetMapping(value = "/hi")
    String home(@RequestParam(value = "name", defaultValue = "forezp") String name);

}

/**
 * 打印错误信息
 */
@Slf4j
@Component
class FeignFallbackFactoryHystric implements FallbackFactory<IFeignService> {

    @Override
    public IFeignService create(Throwable throwable) {
        return new IFeignService(){

            @Override
            public String home(String name) {
                log.error("========查询出错=========", throwable);
                return throwable.getMessage();
            }
        };
    }
}

/**
 * 返回默认实现
 */
@Slf4j
@Component
class FeignFallbackHystric implements IFeignService{
    @Override
    public String home(String name) {
        log.warn("=======查询失败，使用默认值========");
        return "sorry "+name;
    }
}
